package com.ndkj.blog.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * 后台控制：http://localhost:8080/druid/
 **/
@Configuration
public class DruidConfig {

    /**
     * 将配置文件中的对象绑定到这里，注册到spring容器中
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidSource() {
        return new DruidDataSource();
    }

    /**
     * Druid后台监控,相当于Servlet的web.xml
     * 因为SpringBoot内置了Servlet容器，所以没有web.xml,替代方法：ServletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> statViewServletServletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //后台需要有人登录，账号密码配置
        HashMap<String, String> initParameters = new HashMap<>();
        //登陆的key是固定的
        initParameters.put("loginUsername", "lygoup@163.com");
        initParameters.put("loginPassword", "qsx.com3");
        //value允许谁可以访问,null代表所有人，localhost本地用户,特定字符串特定用户
        initParameters.put("allow", "");
        //禁止谁不可以访问,key-UserName,value-IPAddress
        //initParameters.put("liu","192.168.199.67");
        statViewServletServletRegistrationBean.setInitParameters(initParameters);
        return statViewServletServletRegistrationBean;
    }

    /**
     * Druid-Filter
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        HashMap<String, String> initParameters = new HashMap<>();
        //这些东西不进行后台统计
        initParameters.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
        return bean;
    }

}
